package com.admission.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.axis.utils.StringUtils;
import org.apache.commons.fileupload.RequestContext;

public class FileUtils {

	public static String getProjectRoot() {
		String root = RequestContext.class.getResource("/").getFile();
		String pathString = null;
		try {
			pathString = new File(root).getParentFile().getParentFile()
					.getCanonicalPath();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return pathString;
	}

	/**
	 * 从properties文件查找属性，如果没有，则返回默认值,并插入文件,否则,如果increase为true，这+1，否则返回原值,
	 * 此处方法针对浏览人数
	 * 
	 * @param path
	 * @param key
	 * @param defValue
	 * @param isIncrease
	 * @return
	 */
	public static synchronized String getProperties(String path, String key,
			String defValue, boolean isIncrease) {
		String value = "";
		FileInputStream in;
		try {
			in = new FileInputStream(path);

			Properties p = new Properties();
			// 如果此处直接 使用 visitFile 会报错，找不到文件。
			p.load(in);
			in.close();
			value = p.getProperty(key);
			if (StringUtils.isEmpty(value)) {
				p.setProperty(key, defValue);
				FileOutputStream out = new FileOutputStream(path);
				p.store(out, "visit update!");// 存储修改后属性
				out.close();
				return defValue;
			} else {
				if (!isIncrease) {
					return value;
				}
				long num = Long.valueOf(value);
				num++;
				value = String.valueOf(num);
				p.setProperty(key, value);
				FileOutputStream out = new FileOutputStream(path);
				p.store(out, "visit update!");// 存储修改后属性
				out.close();
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	}

	// public static void main(String[] args) {
	//
	// File f = new File("c:/");
	// String regx = "recruitment-detail.*";
	// File[] s = f.listFiles(new FileFilter(regx));
	// System.out.println();
	// }

}
